/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.io.File;
import java.util.Calendar;
import javax.swing.JOptionPane;

/**
 *
 * @author Antonio
 */
public class CreateProduct extends javax.swing.JFrame {

   int block;
   int fk_Run;
   String identifile;
   int length;
   int height;
   int trash;
   int density;
   String hourMinute;
   
   String type;
   String dia;
   String mes;
   String annio;
   String hour;
   String minute;
   
    
    public CreateProduct() 
    {
        initComponents();
    }
   
    public CreateProduct(String type, int id) 
    {
        initComponents();
 
       this.setResizable(false);
       this.type = type;
       this.fk_Run = id;
        System.out.println("EL ID AL QUE INSERTARE ESSS  "+ fk_Run);
       block = 1;
       jLabelBock.setText(Integer.toString(block));
       jTextType.setText(this.type);
        fecha();        
    }
 /**
  * Metodo que es llamado si modifico el tipo de producto
  * @param block 
  */
    public CreateProduct (int block, String type, int id)
    {
        initComponents();
        this.fk_Run=id;
        this.block = block;
        this.type = type;
        System.out.println("create block" +this.block);
        System.out.println("EL ID AL QUE INSERTARE ESSS  "+ fk_Run);
        jLabelBock.setText(Integer.toString(this.block));
        jTextType.setText(this.type);
        fecha();  
    }
    
    
    private void fecha()
    {
        Calendar c1 = Calendar.getInstance();
        
        dia = Integer.toString(c1.get(Calendar.DATE));
        mes = Integer.toString(c1.get(Calendar.MONTH)+1);
        annio = Integer.toString(c1.get(Calendar.YEAR));                
        String date= mes+"/"+dia+"/"+annio;
        jTextDate.setText(date);

    }
    
    private String createIdentifile (String block, String length){
         String year = annio.substring(2);
        identifile = mes+"-"+dia+"-"+year+"-"+block+"-"+length;
         return identifile;
    }
  
    private String getTime(){
        Calendar c2 = Calendar.getInstance();
        
        hour = Integer.toString(c2.get(Calendar.HOUR_OF_DAY));
        minute= Integer.toString(c2.get(Calendar.MINUTE));
        return hour+":"+minute; 
    }
    
    private void pdfDocument(){
           Document documento = new Document();
        
        try {     
             FileOutputStream fichero = new FileOutputStream ("prueba.pdf");
            
             PdfWriter writer = PdfWriter.getInstance(documento, fichero);
             
            // documento.addTitle("Archivo pdf generado desde Java");             
             
             Paragraph paragraph1 = new Paragraph();
             paragraph1.add(" \n Date: "+ mes+"/"+dia+"/"+annio+ "  ");
             paragraph1.setAlignment(paragraph1.ALIGN_LEFT);

             
             Paragraph paragraph2 = new Paragraph(""+identifile,FontFactory.getFont("Arial",   // fuente
				40,                            // tamaño
				Font.BOLD,                   // estilo
				BaseColor.BLACK));              // color
             paragraph2.setAlignment(paragraph2.ALIGN_CENTER);
       
                   
             Paragraph paragraph = new Paragraph();
             paragraph.add(" \n \n \n Length: "+ jTextLength.getText());
             paragraph.add("  \n Height: "+ jTextHeight.getText());
             paragraph.setAlignment(Paragraph.ALIGN_LEFT);
             
              Paragraph paragraph3 = new Paragraph();
             paragraph3.add(" Time: "+ hour+":"+minute);
             paragraph3.setAlignment(paragraph3.ALIGN_LEFT);
             
             
            documento.open();
                
            Image image = Image.getInstance("Dylant.JPG");
              
            documento.add(image);
            documento.add(paragraph1);
            documento.add(paragraph2);
            documento.add(paragraph);
            documento.add(paragraph3);
            documento.close();
           
             
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CreateProduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(CreateProduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(CreateProduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CreateProduct.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
            try {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "prueba.pdf");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    
    
    private void insertProduct(){
        Conexion conexion = new Conexion();
        String query;
        conexion.starConexion();
        query = "insert into Product (Block,Identifile,Type,Length,Height,Trash,"
                + "Density,hour,Fk_run) values ("+block+",'"+identifile+"','"+
                type+"',"+length+","+height+","+trash+","+density+",'"+
                hourMinute+"',"+fk_Run+")";
        
       System.out.println(query);
       conexion.execute(query);        
       conexion.closeConexion();
      
    }
           
   @Override
    public java.awt.Image getIconImage() {
        java.awt.Image retValue = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("image/logo.png"));
       return retValue;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelBock = new javax.swing.JLabel();
        jTextHeight = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextLength = new javax.swing.JTextField();
        jButtonGenerate = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButtonClose = new javax.swing.JButton();
        jTextDate = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButtonChage = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jCheckTrash = new javax.swing.JCheckBox();
        jCheckDensity = new javax.swing.JCheckBox();
        jLabel6 = new javax.swing.JLabel();
        jTextType = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImage(getIconImage());
        setMaximumSize(new java.awt.Dimension(800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));

        jLabelBock.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabelBock.setText("kk");

        jTextHeight.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jTextHeight.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextHeightKeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel2.setText("Height:");

        jTextLength.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jTextLength.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextLengthKeyTyped(evt);
            }
        });

        jButtonGenerate.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jButtonGenerate.setText("Generate");
        jButtonGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGenerateActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel3.setText("Length:");

        jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel4.setText("Block:");

        jButtonClose.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jButtonClose.setText("Close Run");
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });

        jTextDate.setText("fecha");

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel1.setText("Trash:");

        jButtonChage.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jButtonChage.setText("Change Type");
        jButtonChage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonChageActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel5.setText("Density:");

        jCheckTrash.setPreferredSize(new java.awt.Dimension(30, 30));
        jCheckTrash.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jCheckDensity.setPreferredSize(new java.awt.Dimension(30, 30));
        jCheckDensity.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jLabel6.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel6.setText("Type:");

        jTextType.setEditable(false);
        jTextType.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(231, 231, 231)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(129, 129, 129)
                        .addComponent(jButtonGenerate, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addGap(94, 94, 94)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jCheckDensity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelBock, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCheckTrash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextType, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
                            .addComponent(jTextLength)
                            .addComponent(jTextHeight))))
                .addContainerGap(209, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTextDate, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(45, 45, 45))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButtonChage, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(322, 322, 322))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jTextDate)
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelBock, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextType, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextLength, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jCheckTrash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jCheckDensity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonGenerate, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButtonChage, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(90, Short.MAX_VALUE))
        );

        jLabelBock.getAccessibleContext().setAccessibleName("LabelBlock");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGenerateActionPerformed

        if (jCheckTrash.isSelected()){
            trash= 1;
            jCheckTrash.setSelected(false);
        }
        
        if (jCheckDensity.isSelected()){
            density=1;
            jCheckDensity.setSelected(false);
        }
   
        hourMinute = getTime();
        
        identifile = createIdentifile(Integer.toString(block), jTextLength.getText());
        length=Integer.parseInt(jTextLength.getText());
        height=Integer.parseInt(jTextHeight.getText());
        
        insertProduct();
        
        pdfDocument();           
     
        block++;
        jLabelBock.setText(Integer.toString(block));
        jTextLength.setText("");
        jTextHeight.setText("");
        trash=0;
        density=0;
        
    }//GEN-LAST:event_jButtonGenerateActionPerformed

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
        int reply  = JOptionPane.showConfirmDialog(null,"are you sure to close the run?","Close Run",JOptionPane.YES_NO_OPTION);
       if (reply == JOptionPane.YES_OPTION) 
       {
         Home home = new Home();
         home.setVisible(true);
         this.setVisible(false);
       }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jButtonChageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonChageActionPerformed

       int reply  = JOptionPane.showConfirmDialog(null,"are you sure to change type product?","Change Type",JOptionPane.YES_NO_OPTION);
       if (reply == JOptionPane.YES_OPTION) {
        Run run = new Run(block,fk_Run);
                run.setVisible(true);
                this.setVisible(false);
       }
       else
       {
       
       }
    }//GEN-LAST:event_jButtonChageActionPerformed

    private void jTextLengthKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextLengthKeyTyped
        char car = evt.getKeyChar();
        if(jTextLength.getText().length()>=4) evt.consume();
        if((car<'0' || car>'9')) evt.consume();
    }//GEN-LAST:event_jTextLengthKeyTyped

    private void jTextHeightKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextHeightKeyTyped
        char car = evt.getKeyChar();
        if(jTextHeight.getText().length()>=4) evt.consume();
        if((car<'0' || car>'9')) evt.consume();
    }//GEN-LAST:event_jTextHeightKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CreateProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CreateProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CreateProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CreateProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CreateProduct().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonChage;
    private javax.swing.JButton jButtonClose;
    private javax.swing.JButton jButtonGenerate;
    private javax.swing.JCheckBox jCheckDensity;
    private javax.swing.JCheckBox jCheckTrash;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelBock;
    private javax.swing.JLabel jTextDate;
    private javax.swing.JTextField jTextHeight;
    private javax.swing.JTextField jTextLength;
    private javax.swing.JTextField jTextType;
    // End of variables declaration//GEN-END:variables
}
